package com.apes.framework.plugin.form.parser.element;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.plugin.filereader.xml.ApesElementParser;
import com.apes.framework.plugin.form.parser.node.FormNodeParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 功能：tables解析
 *
 * @author cxm
 * @create 2020-08-04 16:12
 */
@Component
public class TablesElementParser implements ApesElementParser<ApesElement, List<Map>> {

    /**
     * 可解析的元素列表
     **/
    private final String[] elementNames = {"tables"};

    /**
     * 功能：可解析节点域
     */
    @Override
    public String getDomain() {
        return FormNodeParser.domain;
    }

    /**
     * 功能：可解析的元素列表
     */
    @Override
    public String[] getNames() {
        return elementNames;
    }

    @Override
    public List parse(ApesElement element) {
        return element.getNestedElements().stream()
                .filter(e -> e.getName().equals("table"))
                .map((Function<ApesElement, Object>) apesElement -> {
                    Map row = (Map) (((Map) apesElement.parse()).get("templateOptions"));
                    if (!StringUtils.isEmpty(apesElement.getText())) {
                        JSONObject json = JSON.parseObject(apesElement.getText());
                        row.putAll(json);
                    }
                    return row;
                }).collect(Collectors.toList());
    }

}
